//
//  SearchInfoViewController.m
//  Cunli
//
//  Created by lilubin on 15/7/3.
//  Copyright (c) 2015年 lilubin. All rights reserved.
//

#import "SearchInfoViewController.h"
#import "LMComBoxView.h"
#import "UIViewExt.h"
#import "MyDataService.h"
#import "NSString+MD5.h"
#import "Config.h"
#import "MJRefresh.h"
#import "MBProgressHUD.h"
#import "SearchInfoModel.h"
#import "SearchInfoLearnModel.h"
#import "NewsCell.h"
#import "NewDetailController.h"
#import "SearchLearCell.h"
#import "BookDetailVC.h"
#import "MediaDetailVC.h"

#define pageSize 6
#define kScreenWidth [UIScreen mainScreen].bounds.size.width
#define kScreenHeight [UIScreen mainScreen].bounds.size.height


static NSString *kNewsCellID = @"NewsCell";
static NSString *kSearchLearnCell = @"SearchLearCell";

@interface SearchInfoViewController () <LMComBoxViewDelegate, UITableViewDataSource, UITableViewDelegate>
{
    NSInteger _searchType;
    NSMutableArray *_datasArray; //存放newsModel的数组
}

@property (nonatomic, strong) UITextField *searchTextfield; //搜索输入框

@property (nonatomic, strong) UITableView *searchTableView; //搜索结果展示的tableview
@end

@implementation SearchInfoViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    _searchType = 1;
    self.view.backgroundColor = [UIColor whiteColor];
    [self setAllUIKitsAttributes];
    [self registerTableViewCell];
//    [self addRefreshAttribute];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)addRefreshAttribute
{
    __weak typeof(self) weakSelf = self;
    
//    [self.searchTableView addLegendHeaderWithRefreshingBlock:^{
//        [weakSelf reloadDataToNew:YES]; //刷新
//    }];
    
    [self.searchTableView addLegendFooterWithRefreshingBlock:^{
        [weakSelf reloadDataToNew:NO]; //加载更多
    }];
    
}


- (void)registerTableViewCell
{
    UINib *nib = [UINib nibWithNibName:@"NewsCell" bundle:nil];
    [_searchTableView registerNib:nib forCellReuseIdentifier:kNewsCellID];
    
    UINib *learnNib = [UINib nibWithNibName:@"SearchLearCell" bundle:nil];
    [_searchTableView registerNib:learnNib forCellReuseIdentifier:kSearchLearnCell];
}

- (void)setAllUIKitsAttributes
{
    self.navigationItem.title = @"搜索";
    NSUInteger searchTextWidth = kScreenWidth-120-8; //kScreenWidth = 20+60+searchTextWidth+60+20
    _datasArray = [NSMutableArray arrayWithCapacity:1];
    LMComBoxView *mlmBox = [[LMComBoxView alloc] initWithFrame:CGRectMake(4, 8, 60, 40)];
    mlmBox.backgroundColor = [UIColor whiteColor];
    mlmBox.titlesList = [NSMutableArray arrayWithObjects:@"资讯", @"学习", nil];
    mlmBox.btnBgImgStr = @"searchLeft.png";
    mlmBox.delegate = self;
    mlmBox.supView = self.view;
    [mlmBox defaultSettings];
    [self.view addSubview:mlmBox];
    
    _searchTextfield = [[UITextField alloc] initWithFrame:CGRectMake(mlmBox.right, 8, searchTextWidth, 40)];
    [_searchTextfield.layer setBorderColor:[UIColor lightGrayColor].CGColor];
    _searchTextfield.placeholder = @"输入搜索内容";
    [_searchTextfield.layer setBorderWidth:1.3];
    [self.view addSubview:_searchTextfield];
    
    UIButton *searchBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    searchBtn.frame = CGRectMake(_searchTextfield.right, 8, 60, 40);
    [searchBtn setBackgroundImage:[UIImage imageNamed:@"searchRightBg"] forState:UIControlStateNormal];
    [searchBtn setTitle:@"搜索" forState:UIControlStateNormal];
    [searchBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [searchBtn.titleLabel setFont:[UIFont boldSystemFontOfSize:17]];
    [searchBtn addTarget:self action:@selector(searchAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:searchBtn];
    
    _searchTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 58, kScreenWidth, kScreenHeight-58-64) style:UITableViewStyleGrouped];
    _searchTableView.delegate = self;
    _searchTableView.dataSource = self;
    _searchTableView.backgroundColor = [UIColor whiteColor];
    self.searchTableView.rowHeight = 90;
    [self.view addSubview:_searchTableView];
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 1;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 1;
}

#pragma - mark LMBoxDelegate
-(void)selectAtIndex:(int)index inCombox:(LMComBoxView *)_combox
{
//    NSLog(@"index:%d, title:%@", index, _combox.titlesList[index]);
    _searchType = index + 1;
}

- (void)searchAction:(UIButton *)button
{
    if (_searchTextfield.text.length != 0)
    {
        [self.view endEditing:YES];
        [self reloadDataToNew:YES];
        [self addRefreshAttribute];
    }
    else
    {
        [self showHudWithStr:@"请输入搜索内容" andImgStr:@"error"];
    }
}

- (void)reloadDataToNew:(BOOL)new
{
    NSMutableDictionary *CheckParams = [NSMutableDictionary dictionaryWithCapacity:5];
    NSString *typeStr = [NSString stringWithFormat:@"%ld", (long)_searchType];
    NSUInteger page = 1;
    if (!new)  // new = NO 设置page
    {
        page = _datasArray.count/pageSize + 1; //根据当前数据数组中的数据量来判断应该加载第几页
    }
    
    NSString *pageStr = [NSString stringWithFormat:@"%lu", page];
    
    [CheckParams setObject:[Config getOwnUserID] forKey:@"userid"];
    [CheckParams setObject:typeStr forKey:@"type"];
    [CheckParams setObject:pageStr forKey:@"page"];
    [CheckParams setObject:@"6" forKey:@"pagesize"];
    [CheckParams setObject:_searchTextfield.text forKey:@"keyword"];
    
    NSString *resultSign = [NSString getSignFromParam:CheckParams andSession:[Config getOwnSession]];
    [CheckParams setObject:resultSign forKey:@"sign"];

    [MyDataService requestURL:@"search.php" httpMethod:@"GET" params:CheckParams fileDatas:nil complection:^(id result) {
        NSLog(@"In SearchVC:%@", result);
        if ([result[@"response"] isEqualToString:@"search"]) {
            NSDictionary *artlistDic = result[@"artlist"];
            NSArray *newsList = artlistDic[@"list"];
            NSInteger totalCount = [artlistDic[@"totalcount"] integerValue];
            
            if (new) {
                if (_datasArray.count != 0) {
                    [_datasArray removeAllObjects];
                }
            }
            
            if (totalCount == _datasArray.count) {
                [self showHudWithStr:@"没有相关内容" andImgStr:@"done"];
            }
            else
            {
                for(NSDictionary *dataDic in newsList)
                {
                    if (_searchType == 1) {
//                        SearchInfoModel *infoModel = [[SearchInfoModel alloc] initWithDataDic:dataDic];
                        SearchInfoModel *infoModel = [SearchInfoModel yy_modelWithJSON:dataDic];
                        [_datasArray addObject:infoModel];
                    }
                    else
                    {
//                        SearchInfoLearnModel *infoLearnModel = [[SearchInfoLearnModel alloc] initWithDataDic:dataDic];
                        SearchInfoLearnModel *infoLearnModel = [SearchInfoLearnModel yy_modelWithJSON:dataDic];
                        [_datasArray addObject:infoLearnModel];
                    }
                }
            }
            dispatch_async(dispatch_get_main_queue(), ^{
//                [self.searchTableView.legendHeader endRefreshing];
                [self.searchTableView.legendFooter endRefreshing];
                [self.searchTableView reloadData];
            });
        }
        else
        {
            NSDictionary *errorDic = result[@"error"];
            [self showHudWithStr:errorDic[@"text"] andImgStr:@"error"];
        }
    } failureAction:^{
        [self showHudWithStr:@"搜索错误" andImgStr:@"error"];
    }];
}

#pragma - mark UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _datasArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (_searchType == 1) {
        NewsCell *cell = [tableView dequeueReusableCellWithIdentifier:kNewsCellID forIndexPath:indexPath];
        cell.cellType = NewsCellSearch;
        cell.searchNewsModel = _datasArray[indexPath.row];
        return cell;
    }
    
    SearchLearCell *cell = [tableView dequeueReusableCellWithIdentifier:kSearchLearnCell forIndexPath:indexPath];
    cell.learnModel = _datasArray[indexPath.row];
    return cell;
}

/*
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 90;
}
 */

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (_searchType == 1) {
        NewDetailController *newDetailVC = [[NewDetailController alloc] init];
        SearchInfoModel *newModel2 = _datasArray[indexPath.row];
        newDetailVC.itemID = newModel2.itemid;
        newDetailVC.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:newDetailVC animated:YES];
    }
    else
    {
        SearchInfoLearnModel *learnModel = _datasArray[indexPath.row];
        if ([learnModel.mttype isEqualToString:@"图书"]) {
            BookDetailVC *bookVC = [[BookDetailVC alloc] init];
            bookVC.bookID = learnModel.itemid;
            bookVC.hidesBottomBarWhenPushed = YES;
            [self.navigationController pushViewController:bookVC animated:YES];
        }
        else
        {
            MediaDetailVC *mediaVC = [[MediaDetailVC alloc] init];
            mediaVC.mediaID = learnModel.itemid;
            mediaVC.hidesBottomBarWhenPushed = YES;
            [self.navigationController pushViewController:mediaVC animated:YES];
        }
    }
}

- (void)showHudWithStr:(NSString *)text andImgStr:(NSString *)imgStr
{
    MBProgressHUD *hud = [Config createHUD];
    hud.mode = MBProgressHUDModeCustomView;
    hud.customView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:imgStr]];
    hud.labelText = text;
    [hud hide:YES afterDelay:1];
}



@end
